package com.whfc.common.util;


import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.layout.font.FontProvider;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayOutputStream;
import java.net.URL;

/**
 * @Description itextPdf工具类
 * @Author hw
 * @Date 2021-07-15 15:45
 * @Version 1.0
 */
public class ItextPdfUtil {

    private static final String FONT = "simhei.ttf";

    private static final Logger logger = LoggerFactory.getLogger(ItextPdfUtil.class);

    @Deprecated
    public static ByteArrayOutputStream htmlToPdf(String html) {
        ConverterProperties props = new ConverterProperties();
        FontProvider fontProvider = new DefaultFontProvider();
        fontProvider.addSystemFonts();
        props.setFontProvider(fontProvider);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        com.itextpdf.kernel.pdf.PdfWriter writer = new com.itextpdf.kernel.pdf.PdfWriter(bao);
        com.itextpdf.kernel.pdf.PdfDocument pdf = new com.itextpdf.kernel.pdf.PdfDocument(writer);
        com.itextpdf.layout.Document document = HtmlConverter.convertToDocument(html, pdf, props);
        document.close();
        return bao;
    }

    public static ByteArrayOutputStream htmlToPdf(String html, String headerImgUrl, String footerImgUrl) {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        try {
            ITextRenderer render = new ITextRenderer();
            ITextFontResolver fontResolver = render.getFontResolver();
            final ClassPathResource font = new ClassPathResource("fonts/simhei.ttf");
            fontResolver.addFont(font.getURL().toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            // 解析html生成pdf
            render.setDocumentFromString(html);
            render.layout();
            render.createPDF(bao);
            if (headerImgUrl != null || footerImgUrl != null) {
                return setHeaderFooter(bao, headerImgUrl, footerImgUrl);
            }
            return bao;
        } catch (Exception e) {
            logger.error("htmlToPdf异常", e);
        }

        return null;
    }

    private static ByteArrayOutputStream setHeaderFooter(ByteArrayOutputStream bao, String headerImgUrl, String footerImgUrl) throws Exception {
        ByteArrayOutputStream retBao = new ByteArrayOutputStream();
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, retBao);
        document.open();
        writer.setPageEvent(new PdfHeaderFooter(headerImgUrl, footerImgUrl));
        PdfContentByte cb = writer.getDirectContent();
        PdfReader reader = new PdfReader(bao.toByteArray());
        Integer pageSize = reader.getNumberOfPages();
        for (int i = 1; i <= pageSize; i++) {
            PdfImportedPage page = writer.getImportedPage(reader, i);
            document.newPage();
            cb.addTemplate(page, 0, 0);
        }
        document.close();
        bao.close();
        return retBao;
    }

}

class PdfHeaderFooter extends PdfPageEventHelper {
    Image headerImage;
    Image footerImage;
    String headerImgUrl;
    String footerImgUrl;

    public PdfHeaderFooter(String headerImgUrl, String footerImgUrl) {
        this.headerImgUrl = headerImgUrl;
        this.footerImgUrl = footerImgUrl;
    }

    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        try {
            if (headerImgUrl != null) {
                headerImage = Image.getInstance(new URL(headerImgUrl));
                headerImage.scalePercent(30);
                headerImage.setAbsolutePosition(document.left(), document.top(8));
                writer.getDirectContent().addImage(headerImage);
            }
            if (footerImgUrl != null) {
                footerImage = Image.getInstance(new URL(footerImgUrl));
                footerImage.scalePercent(30);
                footerImage.setAbsolutePosition(document.right(footerImage.getScaledWidth()), document.bottom());
                writer.getDirectContent().addImage(footerImage);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}